package top.mable.handler;

import com.baomidou.mybatisplus.core.toolkit.AES;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 通过 继承 BaseTypeHandler ，对特定的字段加密处理 。需要在xml的sql文件中，指定
 * #{businessNo , typeHandler=top.mable.handler.EncryptTypeHandler}
 * 或者
 * <result column="status" property="status" typeHandler="top.mable.handler.EncryptTypeHandler"/>
 *
 * @author taffywen
 * @date 2022/3/9 18:40
 */
public class AESEncryptHandler extends BaseTypeHandler {

    String key = "f0ad304a84716b89";

    //非空字段加密
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, AES.encrypt((String) parameter,key));
    }

    //非空字段解密
    @Override
    public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return AES.decrypt(rs.getString(columnName),key);
    }


    @Override
    public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return AES.decrypt(rs.getString(columnIndex),key);
    }

    @Override
    public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return AES.decrypt(cs.getString(columnIndex),key);
    }
}
